package edu.pitt.myptm;

import edu.pitt.myptm.utils.DBUtils;

public class CommandFactory {
	public static MyCommand makeCommand(int type) {
		MyCommand c;
		switch(type) {
		case MyCommand.ABORT:  
			c = new AbortCommand();
			break;
		case MyCommand.BEGIN:
			c = new BeginCommand();
		case MyCommand.COMMIT:
			c = new CommitCommand();
		case MyCommand.DELETE:
			c = new DeleteCommand();
		case MyCommand.MATCH:
			c = new MatchCommand();
		case MyCommand.READ:
			c = new ReadCommand();
		case MyCommand.WRITE:
			c = new WriteCommand();
		default: 
			c = new MyCommand();
            break;
		}
		return c;
	}
	
	public static MyCommand makeCommand(String line,int id,int timestampIndex) {
		MyCommand command = null;
		if(line.startsWith("B")) {
			BeginCommand c = new BeginCommand();
			String[] strs = line.split(" ");
			if(strs[1].trim().contains("1")) {
				c.setTransaction();
			} else {
				c.setProcess();
			}
			command = c;
		} else if(line.startsWith("A")){
			AbortCommand c = new AbortCommand();
			command = c;
		} else if(line.startsWith("C")) {
			CommitCommand c = new CommitCommand();
			command = c;
		} else if(line.startsWith("D")) {
			DeleteCommand c = new DeleteCommand();
			String[] strs = line.split(" ");
			c.setFilename(DBUtils.genFilename(strs[1].trim()));
			command = c;
		} else if(line.startsWith("M")) {
			MatchCommand c = new MatchCommand();
			String[] strs = line.split(" ");
			c.setFilename(DBUtils.genFilename(strs[1].trim()));
			c.setAreacode(strs[2].trim());
			command = c;
		} else if(line.startsWith("R")) {
			ReadCommand c = new ReadCommand();
			String[] strs = line.split(" ");
			c.setFilename(DBUtils.genFilename(strs[1].trim()));
			c.setId(Integer.parseInt(strs[2].trim()));
			command = c;
		} else if(line.startsWith("W")) {
			WriteCommand c = new WriteCommand();
			String[] strs = line.split(" ");
			c.setFilename(DBUtils.genFilename(strs[1].trim()));
			String value = strs[2].trim();
			value = value.substring(1,value.length()-1);
			c.setDataItem(value);
			command = c;
		}
		command.setTransactionId(id);
		command.setTimeStamp(timestampIndex);
		return command;
	}
}
